//
//  SecurityViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/6.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SecurityViewController.h"
#import "GaugeViewController.h"
#import "SecurityCell.h"
#import "GesDatabase.h"
#import "SetGestureLockViewController.h"
#import "OpenGestureLockViewController.h"
#import "VerifyMobileViewController.h"
#import "ChangePasswordViewController.h"
#import "ChangeMobileViewController.h"
#import "SetPayPasswordViewController.h"
#import "SetSafeEMailViewController.h"
#import "SetSafeEmailTwoViewController.h"

@interface SecurityViewController ()<UITableViewDelegate,UITableViewDataSource,HTTPClientDelegate,SetPayPasswordViewControllerDelegate>
{
    GaugeViewController *_gauge;
    
    NSMutableArray *_titleDataArray;
    NSMutableArray *_normalImageDataArray;
    NSMutableArray *_selectImageDataArray;
    NSMutableArray *_detailDataArray;
    
    BOOL _payPasswordStatus;
    BOOL _emailStatus;
    BOOL _mobileStatus;
    NSString *_mobileStr;
    
    NSInteger _securityMark;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) BOOL          isLoading;

@end

@implementation SecurityViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNavBarTitle:@"安全" andLeftItemName:@"返回" andRightItemName:@""];
    
    [self initView];
    [self initData];
}

- (void)viewDidLayoutSubviews {
//    _tableView.frame = RECTMAKE(0, 0, MSWIDTH, MSHIGHT - 64);
//    _gauge.view.frame = CGRectMake(0, 0, MSWIDTH, 300);
    
}

#pragma mark - SetPayPasswordViewControllerDelegate
- (void)setPayPasswordSuccess {
    _payPasswordStatus = YES;
    
}


#pragma mark - Action
- (void)gestureSwitchAction:(UISwitch *)gestureSwitch {
    if (gestureSwitch.on) {
        //设置手势密码
        SetGestureLockViewController *setGesturesVC = [[SetGestureLockViewController alloc]init];
        [self.navigationController pushViewController:setGesturesVC animated:YES];
        
    }else {
        //关闭手势前，需先输入原手势密码
        OpenGestureLockViewController *originalGestureVC = [[OpenGestureLockViewController alloc]init];
        originalGestureVC.type = CloseGesturePwd;
        [self.navigationController pushViewController:originalGestureVC animated:YES];
    }
}

#pragma mark - TableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:     //安全手机
        {
            if (AppDelegateInstance.userInfo.mobile.length > 0) {
                //先验证手机号码
                VerifyMobileViewController *verifyMobile = [[VerifyMobileViewController alloc] init];
                verifyMobile.viewType = ChangeBindMobile;
                verifyMobile.naviTitle = @"更换手机号";
                verifyMobile.mobileStr = AppDelegateInstance.userInfo.mobile;
                [self.navigationController pushViewController:verifyMobile animated:YES];
            }else {
                ChangeMobileViewController *setMobile = [[ChangeMobileViewController alloc] init];
                setMobile.isChangeBank = NO;
                setMobile.backNum = 2;
                setMobile.naviTitle = @"设置手机号";
                setMobile.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:setMobile animated:YES];
            }
        }
            break;
        case 1:     //安全邮箱
        {
            if (AppDelegateInstance.userInfo.mobile.length <= 0) {
                
                return;
            }
            if (AppDelegateInstance.userInfo.isEmailStatus) {
                
                SetSafeEMailViewController *setSafeEMailView = [[SetSafeEMailViewController alloc] init];
//                setSafeEMailView.isSafeQuestion = _isSecretStatus;
                [self.navigationController pushViewController:setSafeEMailView animated:YES];
                
            }else{
                
                
                DLOG(@"确定按钮");
                SetSafeEmailTwoViewController *SetSafeEmailTwoView = [[SetSafeEmailTwoViewController alloc] init];
                [self.navigationController pushViewController:SetSafeEmailTwoView animated:YES];
            }
        }
            break;
        case 2:     //交易密码
        {
            if (_isLoading) {
                [SVProgressHUD showImage:nil status:@"正在加载数据，请稍候..."];
                return;
            }
            if (_payPasswordStatus) {
                //修改交易密码
                SetPayPasswordViewController *changePwd = [[SetPayPasswordViewController alloc] init];
                changePwd.editType = 2;
                [self.navigationController pushViewController:changePwd animated:YES];
            }else {
                //设置交易密码
                SetPayPasswordViewController *changePwd = [[SetPayPasswordViewController alloc] init];
                changePwd.delegate = self;
                changePwd.editType = 1;
                [self.navigationController pushViewController:changePwd animated:YES];
            }
        }
            break;
        case 3:     //登陆密码
        {
            ChangePasswordViewController *changePwd = [[ChangePasswordViewController alloc] init];
            changePwd.naviTitle = @"修改登录密码";
            changePwd.editType = ChangeLoginPwd;
            [self.navigationController pushViewController:changePwd animated:YES];
        }
            break;
        case 4:     //开启or关闭手势密码
        {
            
        }
            break;
        case 5:     //修改手势密码
        {
            //是否开启手势密码
            NSString *account=[[AppDefaultUtil sharedInstance] getDefaultAccount];
            NSString *gestureState=[[GesDatabase getInstance] getGestureState:account];
            if ([gestureState isEqualToString:@"1"]) {
                OpenGestureLockViewController *originalGestureVC = [[OpenGestureLockViewController alloc]init];
                originalGestureVC.type = ModifyGesturePwd;
                [self.navigationController pushViewController:originalGestureVC animated:YES];
            }else {
                [SVProgressHUD showErrorWithStatus:@"请先开启手势密码"];
            }
        }
            break;
            
            
        default:
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _titleDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    SecurityCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"SecurityCell" owner:self options:nil][0];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    }
    cell.leftImageView.image = [UIImage imageNamed:_normalImageDataArray[indexPath.row]];
    cell.titleLabel.text = _titleDataArray[indexPath.row];
    if ([_detailDataArray[indexPath.row] isEqualToString:@"未设置"]) {
        cell.detailLabel.textColor = KColor;
    }else {
        cell.detailLabel.textColor = KGrayColor;
    }
    cell.detailLabel.text = _detailDataArray[indexPath.row];
    
    cell.arrowImageView.hidden = NO;
    cell.detailLabel.hidden = NO;
    cell.gestureSwitch.hidden = YES;
    switch (indexPath.row) {
        case 0:
        {
            
        }
            break;
        case 4:
        {
            cell.detailLabel.hidden = YES;
            cell.arrowImageView.hidden = YES;
            cell.gestureSwitch.hidden = NO;
            
            //是否开启手势密码
            NSString *account = [[AppDefaultUtil sharedInstance] getDefaultAccount];
            NSString *gestureState = [[GesDatabase getInstance] getGestureState:account];
            if ([gestureState isEqualToString:@"1"]) {
                [cell.gestureSwitch setOn:YES];
            }else {
                [cell.gestureSwitch setOn:NO];
            }
            [cell.gestureSwitch addTarget:self action:@selector(gestureSwitchAction:) forControlEvents:UIControlEventValueChanged];
        }
            break;
            
        default:
            break;
    }
    
    
    cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, KAdaptNum(44));
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0f;
}

#pragma mark - 请求数据
- (void)initData {
    _securityMark = 0;
    
    _titleDataArray = [[NSMutableArray alloc] initWithArray:@[@"安全手机",@"安全邮箱",@"交易密码",@"登录密码",@"手势密码",@"手势密码"]];
    _normalImageDataArray = [[NSMutableArray alloc] initWithArray:@[@"security_phone_normal",@"security_mail_normal",@"security_trade_pwd_normal",@"security_login_pwd_select",@"security_gesture_normal",@"security_gesture_normal"]];
    _selectImageDataArray = [[NSMutableArray alloc] initWithArray:@[@"security_phone_select",@"security_mail_select",@"security_trade_pwd_select",@"security_login_pwd_select",@"security_gesture_select",@"security_gesture_select"]];
    _detailDataArray = [[NSMutableArray alloc] initWithArray:@[@"未设置",@"未设置",@"未设置",@"修改",@"未设置",@"未设置"]];
    
    //[self requestData];
    [self reloadData];
}

- (void)reloadData {
    NSInteger securityMark = 20;
    
    _mobileStr = AppDelegateInstance.userInfo.mobile;
    _emailStatus = AppDelegateInstance.userInfo.isEmailStatus;
    _payPasswordStatus = AppDelegateInstance.userInfo.isPayPasswordStatus;
    
    if (_mobileStr.length > 0) {
        [_detailDataArray replaceObjectAtIndex:0 withObject:[NSString phoneNumToAsterisk:_mobileStr]];
        [_normalImageDataArray replaceObjectAtIndex:0 withObject:@"security_phone_select"];
        
        securityMark += 20;
    }else {
        [_detailDataArray replaceObjectAtIndex:0 withObject:@"未设置"];
        [_normalImageDataArray replaceObjectAtIndex:0 withObject:@"security_phone_normal"];
    }
    
    if (_emailStatus) {
        [_detailDataArray replaceObjectAtIndex:1 withObject:@"修改"];
        [_normalImageDataArray replaceObjectAtIndex:1 withObject:@"security_mail_select"];
        
        securityMark += 20;
    }else {
        [_detailDataArray replaceObjectAtIndex:1 withObject:@"未设置"];
        [_normalImageDataArray replaceObjectAtIndex:1 withObject:@"security_mail_normal"];
    }
    
    if (_payPasswordStatus) {
        [_detailDataArray replaceObjectAtIndex:2 withObject:@"修改"];
        [_normalImageDataArray replaceObjectAtIndex:2 withObject:@"security_trade_pwd_select"];
        
        securityMark += 20;
    }else {
        [_detailDataArray replaceObjectAtIndex:2 withObject:@"未设置"];
        [_normalImageDataArray replaceObjectAtIndex:2 withObject:@"security_trade_pwd_normal"];
    }
    
    //是否开启手势密码
    NSString *account=[[AppDefaultUtil sharedInstance] getDefaultAccount];
    NSString *gestureState=[[GesDatabase getInstance] getGestureState:account];
    if ([gestureState isEqualToString:@"1"]) {
        [_detailDataArray replaceObjectAtIndex:4 withObject:@"关闭"];
        [_detailDataArray replaceObjectAtIndex:5 withObject:@"修改"];
        
        [_normalImageDataArray replaceObjectAtIndex:4 withObject:@"security_gesture_select"];
        [_normalImageDataArray replaceObjectAtIndex:5 withObject:@"security_gesture_select"];
        
        securityMark += 20;
    }else {
        [_detailDataArray replaceObjectAtIndex:4 withObject:@"未设置"];
        [_detailDataArray replaceObjectAtIndex:5 withObject:@"未设置"];
        
        [_normalImageDataArray replaceObjectAtIndex:4 withObject:@"security_gesture_normal"];
        [_normalImageDataArray replaceObjectAtIndex:5 withObject:@"security_gesture_normal"];
    }
    
    if (_securityMark != securityMark) {
        _gauge.score = [NSString stringWithFormat:@"%ld",(long)securityMark];
        if (securityMark <= 20) {
            _gauge.levelLabel.text = @"低";
            _gauge.levelLabel.textColor = TwentyColor;
        }else if (securityMark>20 && securityMark<=40) {
            _gauge.levelLabel.text = @"低";
            _gauge.levelLabel.textColor = FourtyColor;
        }else if (securityMark>40 && securityMark<=60) {
            _gauge.levelLabel.text = @"中";
            _gauge.levelLabel.textColor = SixtyColor;
        }else if (securityMark>60 && securityMark<=80) {
            _gauge.levelLabel.text = @"高";
            _gauge.levelLabel.textColor = EightyColor;
        }else {
            _gauge.levelLabel.text = @"高";
            _gauge.levelLabel.textColor = HundredColor;
        }
        _securityMark = securityMark;
    }
    
    
    [_tableView reloadData];

}


- (void)requestData {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"138" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"user_id"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}


#pragma - 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
}

// 返回成功
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    NSDictionary *dics = obj;
    DLOG(@"dic=%@",dics);
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        
        if (dics[@"mobile"] && ![dics[@"mobile"] isKindOfClass:[NSNull class]]) {
            _mobileStr = [NSString stringWithFormat:@"%@",dics[@"mobile"]];
        }
        _payPasswordStatus = [dics[@"payPasswordStatus"] boolValue];
        _emailStatus = [dics[@"emailStatus"] boolValue];
        
        [self reloadData];
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        
        [SVProgressHUD showImage:nil status:[dics objectForKey:@"msg"]];
    }
    
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
}

// 无可用的网络
- (void)networkError {
    //  [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
    _isLoading = NO;
}



#pragma mark - View
- (void)initView {
    _tableView.frame = RECTMAKE(0, 0, MSWIDTH, MSHIGHT - 64);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.estimatedRowHeight = KAdaptNum(44);
    _tableView.bounces = YES;
    
    _gauge = [[GaugeViewController alloc] initWithNibName:@"GaugeViewController" bundle:nil];
    _gauge.view.frame = RECTMAKE(0, 0, MSWIDTH, 300);
    self.tableView.tableHeaderView = _gauge.view;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
